﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Xunit;

namespace NMigrate.Tests
{
	public class MigrationResultTester
	{
		private MigrationResult migrationResult;

		public MigrationResultTester(MigrationResult migrationResult)
		{
			this.migrationResult = migrationResult;
		}

		public class AssertWasCalledFluent
		{
			private VersionMigrationResult versionMigration;
			private MigrationResultTester migrationResultTester;

			public AssertWasCalledFluent(VersionMigrationResult versionMigration, MigrationResultTester migrationResultTester)
			{
				this.versionMigration = versionMigration;
				this.migrationResultTester = migrationResultTester;
			}
			public AssertWasCalledFluent Then(params string[] fileNames)
			{
				var nextVersion = NextVersion();
				foreach(var file in fileNames)
				{
					if(nextVersion == null)
					{
						Assert.False(true, "No version migration more than v " + versionMigration.VersionNumber + " were found in the migration result");
					}
					var fileMigration = nextVersion.FileMigrationResults.FirstOrDefault(o => o.File.Name == file);
					if(fileMigration == null)
					{
						Assert.False(true, "No migration result for " + file + " were found in migration version " + nextVersion.VersionNumber);
					}
				}
				return new AssertWasCalledFluent(nextVersion, migrationResultTester);
			}

			private VersionMigrationResult NextVersion()
			{
				return migrationResultTester.migrationResult.VersionMigrationResults.FirstOrDefault(v => v.VersionNumber > versionMigration.VersionNumber);
			}

			[DebuggerHidden]
			public void ThenNothing()
			{
				if(NextVersion() != null)
				{
					Assert.False(true, "should not find a next version after v " + versionMigration.VersionNumber);
				}
			}
		}


		public MigrationResult Result
		{
			get
			{
				return migrationResult;
			}
		}


		[DebuggerHidden]
		public AssertWasCalledFluent AssertWereCalled(params string[] fileNames)
		{
			var versionMigration = migrationResult.VersionMigrationResults.FirstOrDefault();
			foreach(var file in fileNames)
			{
				if(versionMigration == null)
				{
					Assert.False(true, "No version migration were found in the migration result");
				}
				var fileMigration = versionMigration.FileMigrationResults.FirstOrDefault(o => o.File.Name == file);
				if(fileMigration == null)
				{
					Assert.False(true, "No migration result for " + file + " were found in migration version " + versionMigration.VersionNumber);
				}
			}
			return new AssertWasCalledFluent(versionMigration, this);
		}
	}
}
